package com.xiaoshu.sentinel;

import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import com.xiaoshu.model.ResultCode;
import com.xiaoshu.model.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 功能说明：
 *
 * @ com.xiaoshu.sentinel
 * <p>
 * Original @Author: deane.jia-贾亮亮,@2020/9/29@15:06
 * <p>
 * Copyright (C)2012-@2020 深圳小树盛凯科技 All rights reserved.
 */
@Service
@Slf4j
public class CustomUrlBlockHandler implements UrlBlockHandler {
    @Override
    public void blocked(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws IOException {
        log.info("[访问次数过多] 访问次数过多");
        httpServletResponse.setHeader("Content-Type", MediaType.APPLICATION_JSON_UTF8_VALUE);
        ResultVo<String> resultCode = new ResultVo<>(ResultCode.Fail, null);
        httpServletResponse.getWriter().write(JSON.toJSONString(resultCode));
    }
}
